package com.archive.forum.controller;

import com.archive.forum.dto.MessageDTO;
import com.archive.forum.dto.MessageSessionDTO;
import com.archive.forum.dto.ResultDTO;
import com.archive.forum.dto.UserDTO;
import com.archive.forum.exception.ExceptionEnum;
import com.archive.forum.mapper.UserMapper;
import com.archive.forum.model.MessageSession;
import com.archive.forum.model.User;
import com.archive.forum.service.MessageService;
import jakarta.servlet.http.HttpServletRequest;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class MessageController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private UserMapper userMapper;

    // 获取私聊列表
    @GetMapping("/messages")
    public String messageList(Model model, @NotNull HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login"; // 添加用户未登录的跳转
        }
        List<MessageSessionDTO> sessions = messageService.listSessions(user.getId());
        model.addAttribute("sessions", sessions);
        model.addAttribute("sessionId", null); // 显式设置 sessionId 为 null
        return "message";
    }

    // 获取特定会话的消息
    @GetMapping("/messages/{sessionId}")
    public String getMessages(@PathVariable Integer sessionId, Model model,HttpServletRequest request) {
        // 获取当前登录用户
        User currentUser = (User) request.getSession().getAttribute("user");
        if (currentUser == null) {
            return "redirect:/login";
        }
        // 获取私聊会话列表
        List<MessageSessionDTO> sessions = messageService.listSessions(currentUser.getId());
        model.addAttribute("sessions", sessions);
        // 获取消息列表
        List<MessageDTO> messages = messageService.listMessages(sessionId, currentUser.getId());
        model.addAttribute("messages", messages);
        model.addAttribute("sessionId", sessionId);
        // 获取会话参与者信息
        MessageSession session = messageService.getSessionById(sessionId);
        if (session != null) {
            // 确定对方用户ID
            Integer otherUserId = session.getUser1Id().equals(currentUser.getId())
                    ? session.getUser2Id() : session.getUser1Id();

            // 获取对方用户信息
            User otherUser = userMapper.selectByPrimaryKey(otherUserId);
            UserDTO otherUserDTO = new UserDTO();
            otherUserDTO.setId(otherUser.getId());
            otherUserDTO.setNickname(otherUser.getNickname());
            otherUserDTO.setAvatarUrl(otherUser.getAvatarUrl());
            model.addAttribute("otherUser", otherUserDTO);
        }

        return "message";
    }

    // 发送消息
    @PostMapping("/messages/send")
    @ResponseBody
    public ResultDTO sendMessage(@RequestParam Integer sessionId,
                                 @RequestParam String content,
                                 HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        messageService.sendMessage(sessionId, user.getId(), content);
        return ResultDTO.okOf();
    }

    // 获取未读消息数
    @GetMapping("/messages/unread-count")
    @ResponseBody
    public ResultDTO getUnreadCount(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        int count = messageService.getUnreadCount(user.getId());
        return ResultDTO.okOf(count);
    }
    @PostMapping("/messages/create-session")
    @ResponseBody
    public ResultDTO createSession(@RequestParam Integer targetUserId, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return ResultDTO.errorOf(ExceptionEnum.NOT_LOGIN);
        }

        // 检查会话是否已存在
        Integer sessionId = messageService.findSessionId(user.getId(), targetUserId);
        if (sessionId == null) {
            // 创建新会话
            sessionId = messageService.createSession(user.getId(), targetUserId);
        }
        return ResultDTO.okOf(sessionId);
    }
    @GetMapping("/messages/{sessionId}/content")
    @ResponseBody
    public List<MessageDTO> getMessages(
            @PathVariable Integer sessionId,
            @SessionAttribute User user) {
        return messageService.listMessages(sessionId, user.getId());
    }
}